const express = require("express");
const db = require("../../config/dbserver.js");
const router = express.Router();
const axios = require("axios");

// 广告
router.get(
  "/",
  async function (req, res, next) {
    // 查询meta video banner 广告
    const type = req.query.type;
    let sql = `
      SELECT * FROM meta   
    `;
    if (type) {
      sql += `
        WHERE platform = ?
      `;
    }
    const dbData = await db.dbQuery(sql, [type]);
    const types = ["banner", "video", "interstitial"];
    const result = {};
    types.forEach((type) => {
      result[type] = dbData.filter((e) => e.type == type && e.use == 1);
    });
    req.data = result;
    next();
  },
  async function (req, res) {
    // const [lat,lng] = req.query.location ? req.query.location.split(":") : [];
    // const ip = getClientIp(req);
    const list = req.data;
    const cityName = req.query.city_name || "";
    // 数据区取数据
    const sql = `
      SELECT * FROM ad_c
    `;
    const dbData = await db.dbQuery(sql);
    const adminSendData = {};
    if (dbData?.[0]) {
      const d = dbData[0];
      Object.assign(adminSendData, {
        showAD: d.show_ad === 1,
        filter: JSON.parse(d.filter),
        cadType: d.cad_type,
        initAd: d.init_ad,
        infinityType: d.infinity_type, // 循环显示项
        infinityDelay: d.infinity_delay,
      });
    }

    const isShowAD = adminSendData.showAD || false;
    const filterCityNames = adminSendData.filter || [];
    // 当前尝试是否包含在列表中
    // const isFilter = filterCityNames.some(
    //   (item) => item.name.includes(cityName) && item.active
    // );
    // 如果改的话用 path
    // const location = {
    //   id: "C23NB62W20TF",
    //   name: "西雅图",
    //   country: "US",
    //   path: "西雅图,华盛顿州,美国",
    //   timezone: "America/Los_Angeles",
    //   timezone_offset: "-07:00"
    // };

    // 包含在列表中则不显示
    // cadType 聚焦 类型广告  video banner interstitial
    // && !isFilter
    res.send({
      code: 200,
      data: {
        show: isShowAD,
        // isShowAD: isShowAD && !isFilter,
        isShowAD: isShowAD,
        // hasCity: isFilter,
        type: adminSendData.cadType,
        initAd: adminSendData.initAd,
        list: list,
        autoNextAd: adminSendData.infinityType,
        autoActiveAdDeleay: adminSendData.infinityDelay,
      },
      message: "success",
    });
  }
);

// 一言根据ip存取 缓存24小时
const ips = {};
const cacheTime = 24 * 60 * 60;
//  if (dbCon) {
//       const timer = dbCon.timer * 1;
//       const now = new Date().getTime() / 1000;
//       console.log(">>>>>>>>>>>>>",now,now - timer)
//       console.log("yiyan =>>>>>>>>>>",now - timer < cacheTime)
//       if (now - timer < cacheTime) {

//         return;
//       }
//     }
router.get("/yiyan", async (req, res) => {
  // 修改为从mysql中 yiyan 表中处理
  // 先取key 如果有就用数据库的数据
  // 没有就获取 然后存入数据库

  const key = req.query.key;
  if (key) {
    const sql = `
    SELECT * FROM yiyan
    WHERE \`key\` = ?
  `;
    const yiArr = await db.dbQuery(sql, [key]);

    if (yiArr.length > 3) {
      const random = Math.floor(Math.random() * yiArr.length);
      const dbCon = yiArr[random];
      // console.log("数据库的一言", dbCon);
      res.send({
        code: 200,
        data: dbCon.content,
        message: "success",
      });
      return;
    }
  }

  axios
    .get("https://v.api.aa1.cn/api/yiyan/index.php")
    .then((resp) => {
      // 缓存数据

      const regex = /<[^>]*>/g;

      // 1. 先去除 HTML 标签
      let plainText = resp.data.replace(regex, "");

      // 2. 去除首尾空格、换行符（\n）、回车符（\r）、制表符（\t）
      plainText = plainText.trim();

      // 3. 去除文本中所有换行符、回车符、制表符
      plainText = plainText.replace(/[\n\r\t]/g, "");

      // 4. 去除特殊字符（根据需求调整，这里保留常见符号，去除控制字符等）
      // 保留字母、数字、中文和常见标点，去除其他特殊字符
      plainText = plainText.replace(
        /[^\u4e00-\u9fa5a-zA-Z0-9,.?!，。？！、；;':"()（）]/g,
        ""
      );

      const sql = `
        INSERT INTO yiyan (\`key\`, content,timer,created_at) VALUES (?, ?,?,now())
      `;

      if (key) {
        db.dbQuery(sql, [
          key,
          plainText,
          String(parseInt(new Date().getTime() / 1000)),
        ]);
      }

      return res.send({
        code: 200,
        data: plainText,
        message: "success",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        data: null,
        message: err,
      });
    });
});

module.exports = router;
